package com.alex.activiti.controller;

import com.alex.activiti.utils.SecurityUtil;
import org.activiti.api.process.model.ProcessDefinition;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private ProcessRuntime processRuntime;
    @Autowired
    private TaskRuntime taskRuntime;

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;

    @Autowired
    private SecurityUtil securityUtil;

    @GetMapping("/test")
    public String test01() {
        System.out.println("processRuntime: " + processRuntime);
        System.out.println("taskRuntime: " + taskRuntime);

        System.out.println("repositoryService: " + repositoryService);
        System.out.println("taskService: " + taskService);
        System.out.println("runtimeService: " + runtimeService);
        System.out.println("historyService: " + historyService);
        return "success";
    }

    /**
     * 部署流程
     */
    @GetMapping("/deployProcess")
    public String deployProcess() {
        repositoryService.createDeployment()
                .addClasspathResource("processes/evection-springboot.bpmn")
                .addClasspathResource("processes/evection-springboot.png")
                .name("出差申请流程-springboot")
                .deploy();
        return "success";
    }

    /**
     * 删除流程定义
     */
    @GetMapping("/deleteProcess")
    public String deleteProcess(String deploymentId) {
        if (StringUtils.isBlank(deploymentId)) {
            return "deploymentId不能为空！";
        }
        repositoryService.deleteDeployment(deploymentId, true);
        return "success";
    }

    /**
     * 查询流程的定义
     */
    @GetMapping("/findProcessDefinition")
    public String findProcessDefinition() {
        Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
        System.out.println("可用的流程定义数量:" + processDefinitionPage.getTotalItems());
        for (ProcessDefinition processDefinition : processDefinitionPage.getContent()) {
            System.out.println("流程定义：" + processDefinition);
        }
        return "success";
    }

    /**
     * 启动流程
     */
    @GetMapping("/startProcess")
    public String startProcess(String processDefinitionKey) {
        if (StringUtils.isBlank(processDefinitionKey)) {
            return "processDefinitionKey不能为空！";
        }
        Authentication authUser = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("启动流程，当前登录用户：" + authUser.getName());
        // 启动流程
        ProcessInstance processInstance = processRuntime.start(
                ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey(processDefinitionKey)
                        .build());
        System.out.println("流程实例id:" + processInstance.getId());
        return "success";
    }

    /**
     * 查询任务并办理
     */
    @GetMapping("/findTaskAndComplete")
    public String findTaskAndComplete() {
        Authentication authUser = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("查询任务并办理，当前登录用户：" + authUser.getName());
        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10));
        System.out.println("代办任务数：" + (tasks != null ? tasks.getTotalItems() : 0));
        if (tasks != null && tasks.getTotalItems() > 0) {
            for (Task task : tasks.getContent()) {
                System.out.println("======循环分割线======");
                System.out.println("任务id：" + task.getId());
                System.out.println("任务名称：" + task.getName());
                taskRuntime.complete(TaskPayloadBuilder
                        .complete()
                        .withTaskId(task.getId())
                        .build());
                System.out.println(authUser.getName() + "完成了任务！");
            }
        }
        return "success";
    }

    /**
     * 查询组任务、拾取和办理
     * 先后用GROUP_otherTeam、GROUP_activitiTeam的用户登录观察
     */
    @GetMapping("/findGroupTaskAndClaimAndComplete")
    public String findGroupTaskAndClaimAndComplete() {
        Authentication authUser = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("查询组任务、拾取和办理，当前登录用户：" + authUser.getName());
        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10));
        System.out.println("代办任务数：" + (tasks != null ? tasks.getTotalItems() : 0));
        if (tasks != null && tasks.getTotalItems() > 0) {
            for (Task task : tasks.getContent()) {
                System.out.println("======循环分割线======");
                System.out.println("任务id：" + task.getId());
                System.out.println("任务名称：" + task.getName());
                // 拾取组任务
                taskRuntime.claim(TaskPayloadBuilder
                        .claim()
                        .withTaskId(task.getId())
                        .build());
                System.out.println(authUser.getName() + "拾取了任务！");

                // 完成任务
                taskRuntime.complete(TaskPayloadBuilder
                        .complete()
                        .withTaskId(task.getId())
                        .build());
                System.out.println(authUser.getName() + "完成了任务！");
            }
        }
        return "success";
    }


}
